package com.youxin.third.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.youxin.base.TPage;
import com.youxin.third.auth.convert.ClientDetailConvert;
import com.youxin.third.auth.entity.dto.ClientDetailDto;
import com.youxin.third.auth.entity.dto.ClientSearch;
import com.youxin.third.auth.model.ClientDetails;
import com.youxin.third.auth.service.ClientDetailService;
import com.youxin.third.auth.service.manager.OAuthManager;
import com.youxin.third.auth.util.ClientUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: ClientDetailServiceImp <br>
 * date: 2020/2/8 11:19 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class ClientDetailServiceImpl implements ClientDetailService {

    @Resource
    private OAuthManager oAuthManager;



    @Override
    public ClientDetailDto getClientDetail(String clientId) {
        ClientDetails clientDetails = oAuthManager.findClientDetails(clientId);
        ClientDetailDto clientDetailDto = ClientDetailConvert.modelToDto(clientDetails);
        return clientDetailDto;
    }

    @Override
    public void saveClientDetail(ClientDetailDto clientDetailDto) {
        ClientDetails clientDetails = ClientDetailConvert.dtoToModel(clientDetailDto);
        clientDetails.setRedirectUri("https://localhost/authorization_code_callback");
        clientDetails.setGrantTypes("authorization_code,password,refresh_token,client_credentials");
        if(StringUtils.isEmpty(clientDetails.getClientId())){
            clientDetails.setClientId(ClientUtil.getClientId());
            clientDetails.setClientSecret(ClientUtil.getClientSecret(clientDetails.getClientId()));
            oAuthManager.saveClientDetails(clientDetails);
        }else {
            oAuthManager.updateByClientDetails(clientDetails);
        }
    }

    @Override
    public TPage<ClientDetailDto> page(ClientSearch clientSearch) {
        LambdaQueryWrapper<ClientDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ClientDetails::getCreateTime);
        IPage<ClientDetails> page = oAuthManager.pageClientDetails(new Page<>(clientSearch.getCurrentPage(),clientSearch.getShowCount()),queryWrapper);
        List<ClientDetailDto> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(page.getRecords())){
            list = page.getRecords().stream().map(item -> ClientDetailConvert.modelToDto(item)).collect(Collectors.toList());
        }
        return TPage.page(list,page.getTotal());
    }
}
